import axios from 'axios';
import qs from 'qs';

class Request {

  public SetConfig: any = {};
  public SetError: any = {};
  private RequestObject: any = {};

  /**
   * 实例一个请求
   */
  public constructor(param: any = {}) {
    this.RequestObject = axios.create(param);
  }

  /**
   *
   * 设置请求拦截器
   */
  public SetRequestInterceptors(): void {
    // 添加请求拦截器
    this.RequestObject.interceptors.request.use((config: any) => {
      // 在发送请求之前做某事
      if (this.SetConfig instanceof Function) {
        return this.SetConfig(config);
      }
      return config;
    }, (error: any) => {
      // 请求错误时做些事
      if (this.SetError instanceof Function) {
        return this.SetError(Promise.reject(error));
      }
    });
  }

  /**
   *
   * 设置请求响应拦截器
   */
  public SetResponseInterceptors(): void {
    // 添加响应拦截器
    this.RequestObject.interceptors.response.use((response: any) => {
      // 对响应数据做些事
      return response;
    }, (error: any) => {
      // 请求错误时做些事
      if (this.SetError instanceof Function) {
        return this.SetError(Promise.reject(error));
      }
    });
  }

  /**
   *
   * get请求
   * @param url 请求的url
   * @param param 请求的参数
   *
   */
  public async Get(url: string, param: any = []): Promise<any> {
    let res = {};
    await this.RequestObject.get(url, {params: param}).then((response: any) => {
      res = response.data;
    });
    return res;
  }

  /**
   *
   * post请求
   * @param url 请求的url
   * @param param 请求的参数
   *
   */
  public async Post(url: string, param: any = []): Promise<any> {
    let res = {};
    await this.RequestObject.post(url, qs.stringify(param)).then((response: any) => {
      res = response.data;
    });
    return res;
  }

}

export default Request;
